import os
import time

import psutil
import subprocess
import re


def kill_max_processes():
    # 获取所有包含"max"的进程
    max_processes = []
    for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
        try:
            # 安全处理可能为None的cmdline
            cmdline = proc.info['cmdline'] or []
            name = proc.info['name'] or ""

            # 检查进程名或命令行参数是否包含"max"
            if ("max" in name.lower()) or any("max" in (part or "").lower() for part in cmdline):
                max_processes.append(proc)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            continue

    if not max_processes:
        print("未找到包含'max'关键字的进程")
        return

    # 终止找到的进程
    for proc in max_processes:
        try:
            proc_name = proc.info.get('name', '未知进程')
            proc_pid = proc.info['pid']
            print(f"终止进程: PID={proc_pid}, 名称={proc_name}")
            proc.kill()
        except Exception as e:
            print(f"无法终止进程 {proc.info['pid']}: {str(e)}")


def release_max_ports():
    # 获取所有网络连接
    connections = psutil.net_connections()
    max_ports = set()

    # 查找包含"max"的进程使用的端口
    for conn in connections:
        if conn.pid:
            try:
                proc = psutil.Process(conn.pid)
                proc_name = proc.name() or ""
                cmdline = " ".join(proc.cmdline() or [])
                if "max" in proc_name.lower() or "max" in cmdline.lower():
                    if conn.laddr and conn.laddr.port:
                        max_ports.add(conn.laddr.port)
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue

    if not max_ports:
        print("未找到与'max'相关的端口占用")
        return

    # 释放端口（实际是通过终止占用进程实现的）
    print("以下端口已被释放:", max_ports)


if __name__ == "__main__":
    print("=== 终止所有'max'相关进程 ===")
    kill_max_processes()

    print("\n=== 释放'max'相关端口 ===")
    release_max_ports()